const fs = require("fs"); // 系统模块 无需安装
const path = require("path"); // 系统模块 无需安装
const { addLog } = require("../utils");
const { exec } = require("child_process");
const nvm = require("../uvm");
let proPath = ''
// 判断是否需要执行npx @dcloudio/uvm
function isUvm(projectName) {
  return new Promise((resolve, reject) => {
    // 读取package.json
    const packageJson =  require(path.join(proPath,'package.json'));
    // 读取@dcloudio/vue-cli-plugin-uni版本
    // 去除版本~^
    const uniAutomatorVersion = packageJson.devDependencies["@dcloudio/vue-cli-plugin-uni"].replace(/\^|~/g,'');
    // npm获取当前@dcloudio/vue-cli-plugin-uni的版本
    const cmdStr = `npm view @dcloudio/vue-cli-plugin-uni version`;
    addLog(`获取cli-基座`,projectName);
    exec(cmdStr, (err, stdout, stderr) => {
      if (err) {
        addLog(`获取cli-基座版本失败:${err}`,projectName);
        reject(false);
      }
      const npmUniAutomatorVersion = stdout.toString().trim().replace(/\^|~/g,'');
      addLog(`当前的cli-基座版本为${uniAutomatorVersion}与最新cli${npmUniAutomatorVersion}${npmUniAutomatorVersion == uniAutomatorVersion?'版本一致':'版本不一致'}`,projectName);
      // 对比版本
      if (uniAutomatorVersion != npmUniAutomatorVersion) {
        console.log("版本不致更新");
        addLog('cli-基座版本更新中',projectName);
        // 执行npx @dcloudio/uvm 
        nvm(proPath,packageJson).then(() => {
          addLog('cli-基座版本更新成功',projectName);
          // 修改package 里面的所有uniAutomatorVersion 为最新版本
          let jsonStr = JSON.stringify(packageJson);
          let oldVersion = new RegExp(uniAutomatorVersion, "g");
          jsonStr = jsonStr.replace(oldVersion, npmUniAutomatorVersion);
          fs.writeFileSync(
            path.join(  proPath,'package.json'),
            jsonStr,'utf-8'
          );
          // 提交git
          addLog('cli-基座版本提交git',projectName);
          exec(`cd ${proPath} && git add . && git commit -m "cli-基座版本更新" && git push`, (err, stdout, stderr) => {
            if (err) {
              addLog('cli-基座版本提交git失败:'+err,projectName);
              reject(false);
            }
            addLog('cli-基座版本提交git成功',projectName);
          })
            

          resolve(true);
        }).catch((err) => {
          addLog('cli-基座版本更新失败:'+err,projectName);
          reject(false);
        });
      }else{
        addLog('cli-基座版本为最新',projectName);
        resolve(true);
      }
    });
  })
}


 function buildPlus({projectName,newSdk,projectPath},{installType}) {
  proPath = projectPath || path.join(__dirname, "../project", projectName);
  return new Promise(async (resolve, reject) => {
    if(newSdk == 'y'){
      addLog('使用最新sdk,开始更新sdk',projectName);
      let bool = false;
      try{
        bool = await isUvm(projectName);
      }catch(err){
        bool = false;
        reject(err);
      }
      if(!bool) return
    }else{
      addLog('不使用最新sdk',projectName);
    }
    const cmdStr = `cd ${proPath} && ${installType}`;
    addLog(`${installType} 开始`,projectName);
    exec(cmdStr, (err, stdout, stderr) => {
      if (err) {
        addLog(`${installType} 失败:${err}`,projectName);
        return reject(err);
      }
      addLog(`${installType} 成功`,projectName);
      // 执行npm run build:app-plus
      const cmdStr2 = `cd ${proPath} && npm run build:app-plus`;

      addLog('npm run build:app-plus 开始',projectName);
      exec(cmdStr2, (err, stdout, stderr) => {
        if (err) {
          addLog(`npm run build:app-plus 失败:${err}，请更换项目装包方式 yarn 方式错误率低`,projectName);
          reject(err);
        }
        addLog('npm run build:app-plus 成功',projectName);
        resolve('npm run build:app-plus 成功')
      })
    })
  })
}




module.exports = {
  buildPlus,
};
